<?php

namespace App\Http\Controllers;

use App\Models\Article\Column;
use App\Models\Article\Comment;
use App\Models\Article\Post;
use Illuminate\Http\Request;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //$this->middleware('auth');
    }

    /**
     * @return string
     */
    public function index()
    {
        return "张敏毕业设计";
    }

    public function getColumn()
    {
        $data = Column::orderBy('order', 'desc')->get(['id', 'name', 'order']);
        return response()->json($data);
    }

    public function getArticleList(Request $request)
    {
        $c_id = $request->input("c_id", 0);

        $column = ['id', 'title', 'describe', 'thumb', 'author', 'source', 'created_at', 'updated_at'];

        if ($c_id > 0) {
            $data = Post::orderBy('id', 'desc')->where('c_id', '=', $c_id)->paginate(20, $column);
        } else {
            $data = Post::orderBy('id', 'desc')->paginate(20, $column);
        }

        foreach ($data as $k => $v) {
            $data[$k]['comments'] = $v->comments()->count();

            $data[$k]['thumb'] = Post::getThumb($v->thumb);

            $data[$k]['url'] = "https://zm.leyix.com/info?id=" . $v->id;
        }

        return response()->json($data);
    }

    public function getCommentList(Request $request)
    {
        $post_id = $request->input("post_id", 0);

        $data = Comment::orderBy('id', 'desc')->where('post_id', '=', $post_id)->paginate(20);
        foreach ($data as $k => $v) {
            $data[$k]['user'] = $v->user()->first(['name', 'email']);
        }
        return response()->json($data);
    }

    public function info(Request $request)
    {
        $id = $request->input("id", 0);
        $info = Post::find($id);

        return view('info', $info);
    }
}
